package com.css.zfzx.sjcj.modules.drill.service.impl;

import com.css.zfzx.sjcj.modules.drill.service.QhDataTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

/**
 * @author tao
 * @date 2020-11-19
 */
@Slf4j
@Service
@PropertySource(value = "classpath:platform-config.yml")
public class QhDataTemplateServiceImpl implements QhDataTemplateService {

    @Value("${file-upload.attachment-directory.config.defaultDirectory.fileDirectory}")
    private String localPath;

    @Override
    public void download(String name, HttpServletResponse response) {
        try {
            String path = localPath + "/excel";//文件的下载地址
            String fullName = name + ".xlsx";
            //设置响应头
            response.reset();//设置页面不缓存
            response.setCharacterEncoding("UTF-8");//字符集编码
            response.setContentType("multipart/form-data");//二进制传输文件
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fullName, "UTF-8"));//设置响应头
            File file = new File(path, fullName);
            //输入流
            FileInputStream inputStream = new FileInputStream(file);
            //输出流
            ServletOutputStream outputStream = response.getOutputStream();

            byte[] bytes = new byte[10240000];
            int index = 0;
            while ((index = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, index);
                outputStream.flush();
            }
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {

        }
    }

}
